package com.fastloan.mgt.application.contract.controller;

import com.fastloan.common.model.CheckResult;
import com.fastloan.mgt.application.contract.dao.ApplicationLoanResultMapper;
import com.fastloan.mgt.application.contract.enums.LoanModeEnum;
import com.fastloan.mgt.application.contract.model.ApplicationLoanResult;
import com.fastloan.mgt.application.contract.service.ApplicationContractService;
import com.fastloan.mgt.application.contract.service.impl.loanmode.mode.ry.RYLoanMode;
import com.fastloan.mgt.application.contract.service.impl.loanmode.mode.ry.model.RyLoanResult;
import com.fastloan.mgt.application.contract.service.impl.loanmode.mode.ry.model.RyRepaymentResult;
import com.fastloan.utils.DateTimeUtil;
import com.kawins.result.ResultEnum;
import com.kawins.result.ResultTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.fastloan.utils.DateTimeUtil.DIGIT_DATETIME_PATTERN;

/**
 * 融钰Controller
 *
 * @author yanwe
 * createTime 2018-01-2018/1/16 15:54
 */
@RestController
@RequestMapping("/api/ry/anon")
public class RyCallBackController {

    @Autowired
    private ApplicationContractService applicationContractService;

    @Autowired
    private RYLoanMode ryLoanMode;

    @PostMapping("/callback/loan")
    public ResultTo loanCallback(@RequestBody RyLoanResult ryLoanResult) {
        ApplicationLoanResult applicationLoanResult = new ApplicationLoanResult();
        applicationLoanResult.setApplicationId(ryLoanResult.getAgent_order_no());
        applicationLoanResult.setLoanMsg(ryLoanResult.getMsg());
        applicationLoanResult.setLoanStatus(ryLoanResult.getRemit_result());
        applicationLoanResult.setLoanTime(DateTimeUtil.format(ryLoanResult.getRemit_time(),DIGIT_DATETIME_PATTERN));
        applicationLoanResult.setLoanNo(ryLoanResult.getOrder_no());
        applicationLoanResult.setLoanModeEnum(LoanModeEnum.R_ONG_YU);
        return applicationContractService.loanCallback(applicationLoanResult);
    }

    @PostMapping("/callback/repayment")
    public ResultTo repaymentCallback(@RequestBody RyRepaymentResult ryRepaymentResult) {
        CheckResult checkResult = ryLoanMode.updateRepaymentPlan(ryRepaymentResult.getAgent_order_no());
        if (!checkResult.isCheckResult()){
            return new ResultTo(ResultEnum.OPERATION_FAILED,checkResult.getCheckMsg());
        }
        return new ResultTo();
    }
}
